import React from 'react';
import { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';

import { Input,Button,Table,message,Modal,Form,Select,Popconfirm,Drawer } from 'antd';


import { role_list, staff_search, staff_del, staff_add, staff_edit } from '../../../utils/api'


const { Option } = Select;
const { Search } = Input;
const { useForm } = Form

function StaffManage(props) {

  //创建Form实例
  var [formInstance] = useForm()



  //点击搜索时执行
  const onSearch = async value => {
    setSearchKey(value);//保存搜索的关键字
    //发起模糊搜索请求
    setLoading(true);
    const data = await staff_search({ searchKey: value, page: 1, count: 10 })
    setStafflist(data.data.list);
    setTotal(data.data.total)
    setLoading(false);
  }

  //页码发生改变时 调用,通过第一个参数pagination获取到最新页码
  var onChange = (pagination) => {
    var { current } = pagination;
    setCurrent(current);//保存页码
    //重新发起分页请求
    setLoading(true);
    staff_search({ searchKey, page: current, count: 10 }).then((res) => {
      setStafflist(res.data.list);
      setTotal(res.data.total);
      setLoading(false);
    })
  };


  // 验证通过时调用
  var onFinish = (values) => {
    
    staff_add(values).then((res) => {
      if (res.data.code === 200) {
        message.success(res.data.msg);

        setVisible(false);//隐藏弹框
      } else {
        message.error(res.data.msg)
      }
    })
  }

  //编辑员工表单 验证通过时 调用
  var onFinishEdit = (values)=>{
    console.log(values);

    staff_edit( values ).then((res)=>{
        if( res.data.code === 200 ){
            message.success(res.data.msg);
            setIsModalVisibleEdit(false);//隐藏弹框
        }else{
            message.error(res.data.msg)
        }
    })
  }


  //点击"确认删除" 调用该方法
  var confirm = (id)=>{
    staff_del({ id, searchKey,page:current,count:10}).then((res)=>{
      console.log(res.data);
      if( res.data.code === 200 ){
        setStafflist( res.data.list );
        setTotal(res.data.total);
        message.success(res.data.msg);
      }
    })
  }

  //点击"取消" 调用该方法
  var cancel = () => {

  }

  //显示"编辑员工"弹框
  var showModalEdit = (text)=>{
    text = JSON.parse( JSON.stringify( text ) );//先深拷贝 text ,避免影响原有数据.
    text.role = text.role._id;//设置角色id
    
    formInstance.setFieldsValue(text); //回显员工信息
    setIsModalVisibleEdit(true);//显示弹框
  }



  const columns = [
    {
      title: '账号', //表格头
      dataIndex: 'user', //表格列的数据索引
      key: 'user',
      width:'150',
          ellipsis: true
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width:'150',
          ellipsis: true
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width:'150',
          ellipsis: true
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width:'150',
          ellipsis: true
    },
    {
      title: '类型',
      key: 'type',
      width:'150',
          ellipsis: true,
      render: val => <span>{val.role.name}</span>
    },
    {
      title: '角色',
      key: 'role',
      width:'150',
          ellipsis: true,
      render: val => <span>{val.role.name}</span>
    },
    {
      title: '操作',
      key: 'age',
      render: text => {
        return (
          <>
            <i onClick={()=>{ showModalEdit(text) }}
             className='iconfont icon-bianji' style={{ marginRight: 15 }}></i>
            <Popconfirm
              title="确认删除该员工吗?"
              onConfirm={() => {confirm(text._id)}}
              onCancel={cancel}
              okText="确定删除"
              cancelText="取消"
            >
              <i className='iconfont icon-shanchu'></i>
            </Popconfirm>
          </>
        )
      },
    },

  ];






  const showDrawer = () => {
    setVisible(true);
  };
  const onClose = () => {
    setVisible(false);
  };

  const handleOk = () => {
    setIsModalVisibleEdit(false);//隐藏弹框
  };
  const handleCancel = () => {
    setIsModalVisibleEdit(false);
};


  //引入组件状态
  //员工列表
  const [stafflist, setStafflist] = useState([])
  //员工总数
  const [total, setTotal] = useState(0)
  //当前页码
  const [current, setCurrent] = useState(1)
  //loading状态
  const [loading, setLoading] = useState(false)
  //搜索关键字
  const [searchKey, setSearchKey] = useState('')
  //弹框是否显示
  const [visible, setVisible] = useState(false);
  //角色列表
  const [rolelist, setRolelist] = useState([])
  //编辑弹框是否显示
  const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false)






  //引入生命周期函数
  useEffect(() => {
    // 请求员工列表
    setLoading(true);
    staff_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
      setStafflist(res.data.list);
      setTotal(res.data.total);
      setLoading(false);
    })

    //请求角色列表
    role_list().then((res) => {
      setRolelist(res.data.list)
    })
  }, [])






  return (
    <div className='staffmanage'>
      <div className='title'>员工管理</div>
      <div className="ope">
        <Search placeholder="搜索员工姓名" onSearch={onSearch} enterButton />
        <Button type="primary" onClick={showDrawer} icon={<PlusOutlined />}>
          新增员工
        </Button>

      </div>

      {/* columns   决定了表格每一列如何渲染 */}
      {/* dataSource    决定了表格每一行有多少行 */}
      <Table
        loading={loading}
        style={{backgroundColor:'white'}} 
        size='small'
        dataSource={stafflist}
        columns={columns}
        pagination={{ current, pageSize: 10, total }}
        onChange={onChange}
      />


      <Drawer
        title="添加新成员"
        width={720}
        onClose={onClose}
        visible={visible}
        bodyStyle={{
          paddingBottom: 80,
        }}

      >
        <Form onFinish={onFinish}>
          <Form.Item label="账号" name="user" rules={[{
            required: true,
            message: '输入账号',
            
          }]}>
            <Input placeholder='请输入账号' />
          </Form.Item>
          <Form.Item label="姓名" name="name" rules={[{
            required: true,
            message: '输入姓名',
          }]}>
            <Input placeholder='请输入姓名' />
          </Form.Item>
          <Form.Item label="昵称" name="nickname" rules={[{
            required: true,
            message: '输入昵称',
          }]}>
            <Input placeholder='请输入昵称' />
          </Form.Item>
          <Form.Item label="手机号" name="phone" rules={[{
            required: true,
            message: '输入手机号',
          }]}>
            <Input placeholder='请输入手机号'/>
          </Form.Item>
          <Form.Item label="角色" name="role" rules={[{
            required: true,
            message: '选择角色',
          }]}>
            <Select defaultValue={'选择角色'} style={{ width: 120 }} >
              {
                rolelist.map((item, index) => {
                  return (
                    <Option value={item._id} key={index}> {item.name} </Option>
                  )
                })
              }
            </Select>
          </Form.Item>

          <Form.Item >
            <Button type="primary" htmlType="submit">
              新增员工
            </Button>
          </Form.Item>
        </Form>

      </Drawer>


      {/* 编辑弹框 */}
      <Modal title="编辑员工" onCancel={handleCancel}  onOk={handleOk} visible={isModalVisibleEdit} >
            {/* form属性的值必须是useForm()创建的Form实例 */}
            <Form form={formInstance}  onFinish={onFinishEdit}>
                <Form.Item hidden label="员工id" name="_id">
                    <Input />
                </Form.Item>
                <Form.Item label="账号" name="user" rules={[{
                    required: true,
                    message: '输入账号',
                    
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="姓名" name="name" rules={[{
                    required: true,
                    message: '输入姓名',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="昵称" name="nickname" rules={[{
                    required: true,
                    message: '输入昵称',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="手机号" name="phone" rules={[{
                    required: true,
                    message: '输入手机号',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="角色" name="role" rules={[{
                    required: true,
                    message: '选择角色',
                    }]}>
                    <Select defaultValue={'选择角色'} style={{ width: 120 }} >
                        {
                            rolelist.map((item,index)=>{
                                return (
                                    <Option value={item._id} key={index}> {item.name} </Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                
                <Form.Item >
                    <Button type="primary" htmlType="submit">
                        更新员工
                    </Button>
                </Form.Item>
            </Form>
      </Modal>

    </div>
  );
}

export default StaffManage;